﻿using System.Windows;
using System.Reflection;
using System.Windows.Data;
using System.Windows.Controls;
using System.Collections.Generic;

using Builderator.Core;

namespace Builderator.Firefly.Controls
{
    /// <summary>
    /// Interaction logic for VariableControl.xaml
    /// </summary>
    public partial class VariableControl : UserControl, IProperty
    {
        public static DependencyProperty VariablesProperty = DependencyProperty.Register("Variables", typeof(VariableDictionary), typeof(VariableControl));

        public new event PropertyChanged OnPropertyChanged;

        private int lastSelected;

        public PropertyInfo Property
        {
            get;
            set;
        }

        public VariableDictionary Variables
        {
            get
            {
                return (VariableDictionary)this.GetValue(VariablesProperty);
            }
            set
            {
                this.SetValue(VariablesProperty, value);

                this.variableDataGrid.ItemsSource = value;

                if (this.OnPropertyChanged != null)
                    this.OnPropertyChanged(this.Property, value);
            }
        }

        private VariableControl()
        {
            InitializeComponent();
        }

        public VariableControl(PropertyInfo property)
            : this()
        {
            this.Property = property;
        }

        private void variableDataGrid_UnloadingRow(object sender, DataGridRowEventArgs e)
        {
            if (e.Row.Item is Variable)
            {
                Variable variable = (Variable)e.Row.Item;

                if (!variable.CanDelete)
                {
                    this.Variables.Insert(this.lastSelected, variable);
                }
            }
        }

        private void variableDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.Column.Header.Equals("CanDelete"))
            {
                e.Column.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private void variableDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.variableDataGrid.SelectedIndex != -1)
            {
                this.lastSelected = this.variableDataGrid.SelectedIndex;
            }
        }
    }
}
